﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.WebControls;
using System.Configuration;

namespace de.rwth.rz.campus.labs.Mailer2010
{
    public class FromField : SPFieldText
    {
        private static Regex regex = new Regex("(?<user>[^@]+)@(?<host>.+)", RegexOptions.IgnoreCase);

        public FromField(SPFieldCollection fields, string fName)
            : base(fields, fName) { }
        public FromField(SPFieldCollection fields, string fName, string dName)
            : base(fields, fName, dName) { }

        // Validate the string. If not valid, throw an SPFieldValidationException
        public override string GetValidatedString(object value)
        {
            if (string.IsNullOrEmpty(value.ToString()) || !regex.IsMatch(value.ToString()))
            {
                throw new SPFieldValidationException("Ihr Account enthält keine gültige E-Mailadresse. Bitte wenden Sie sich an Ihren Administrator.");
            }
            return base.GetValidatedString(value);
        }

        public override string DefaultValue
        {
            get
            {
                string dValue = SPContext.Current.Web.CurrentUser.Email;
                if (string.IsNullOrEmpty(dValue))
                    dValue = "noreply@" + System.Net.Dns.GetHostName();

                return dValue;
            }
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl control = new FromFieldControl();
                control.FieldName = this.InternalName;
                return control;
            }
        }
    }

    public class FromFieldControl : BaseFieldControl
    {
        protected InputFormTextBox FromBox;

        protected override string DefaultTemplateName
        {
            get
            {
                return @"FromFieldTemplate";
            }
        }

        public override object Value
        {
            get
            {
                this.EnsureChildControls();
                return this.FromBox.Text;
            }
            set
            {
                EnsureChildControls();
                this.FromBox.Text = (string)this.ItemFieldValue;
            }
        }

        protected override void CreateChildControls()
        {
            if (this.Field == null || this.ControlMode == SPControlMode.Display)
                return;
            base.CreateChildControls();
            this.FromBox = (InputFormTextBox)TemplateContainer.FindControl("FromBox");

            if (this.FromBox == null)
                throw new ConfigurationErrorsException("Corrupted ControlTemplate.");
        }
    }
    
}
